import { defineStore } from 'pinia';
import { UserState } from './types';
import {
  login as userLogin,
  logout as userLogout,
  LoginData,
  getUserInfo
} from '@/api/login/login';
import { setToken, clearToken, isLogin } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    userId: null,
    username: '',
    nickName: '',
    avatar: '',
    gender: '',
    email: '',
    phone: '',
    status: '',
    registrationDate: '',
    role: '',
    roles: [],
    isLogin: isLogin(),
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // 获取用户信息
    async info() {
      const res = await getUserInfo();
      this.setInfo(res.data);
    },

    // 登录
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        // @ts-ignore
        if (res.code === 200 && res.data) {
          // @ts-ignore
          await setToken(res.data.tokenValue);
          await this.info();
        } else {
          // @ts-ignore
          throw new Error(res.msg);
        }
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      this.resetInfo();
      clearToken();
      removeRouteListener();
    },
    // Logout
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },

    // 更新user
    updateSettings() {
      this.isLogin = isLogin();
    },
  },
});

export default useUserStore;
